package com.wxy.ej.flow.modules.taskflow.service.nodeExecuteStrategy.strategy.controller;

import com.alibaba.fastjson.JSONObject;
import com.rt.easyjava.common.base.Result;
import com.rt.easyjava.common.utils.others.StringUtils;
import com.wxy.ej.flow.modules.taskflow.dto.DataDto;
import com.wxy.ej.flow.modules.taskflow.dto.NodeDto;
import com.wxy.ej.flow.modules.taskflow.service.nodeExecuteStrategy.NodeStrategy;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ControllerIfStartNodeStrategy extends NodeStrategy {
    public static final String IfCondition_True = "IfCondition_True";
    public static final String IfCondition_False = "IfCondition_False";

    @Override
    public Result action(NodeDto node, JSONObject flowDataJson, DataDto dataDto) throws Exception {
        final String IfNodeKey = node.getId()+"_IfNode";
        String ifCondition = node.getIfCondition();
        log.info("ControllerIfStartNodeStrategy: ifcondition: {}", ifCondition);
        dataDto.getLogList().add("条件："+ifCondition);

        // if 只执行一次
        Object currentCircleIndexObj = dataDto.getStorageControllerVarMap().get(IfNodeKey);
        if (currentCircleIndexObj!=null) {
            // 清空状态标志，当循环情况，会再次执行当前if
            dataDto.getStorageControllerVarMap().remove(IfNodeKey);
            return Result.builder(IfCondition_False);
        }
        dataDto.getStorageControllerVarMap().put(IfNodeKey, "if-node-run");

        boolean b = false;

        if (StringUtils.isNull(ifCondition)) {
            b = false;
        }
        else if ("false".equalsIgnoreCase(ifCondition)) {
            b = false;
        }
        else if ("true".equalsIgnoreCase(ifCondition)) {
            b = true;
        }else{
            b = (Boolean) executeScriptForResult(dataDto, ifCondition);
        }

        log.info("ControllerIfStartNodeStrategy: ifcondition result: {}", b);
        dataDto.getLogList().add("执行结果："+b);
        if(b) {
            return Result.builder(IfCondition_True);
        } else {
            return Result.builder(IfCondition_False);
        }

    }


}
